const vm = new Vue({
    el: '#main',
    data: {
        getAuthCodeText: '获取验证码',
        usePwdLogin: false,
        getAuthCodeAble: true,
        reqData: {
            tel: '',
            code: '',
            pwd: '',
        },
        loginUserInfo: {
            openId: '',
            avatar: '',
            gender: '',
            nickName: '',
            Lat: 0,
            Lng: 0,
        },
        loginOrLogUp: 'log in',
        isReqCode: false,
    },
    methods: {
        switchPwdOrAuthCode,
        keyup,
        getAuthCode,
        submit,
    },
});

function apiready() {
    getLocation();
    api.getPhoneNumber(function (ret, err) {
        if (!isExist(err)) {
            vm.reqData.tel = ret.value;
            unBanA('.auth-code-btn');
        }
    });
}

async function getLocation() {
    const bMap = api.require('bMap');
    bMap.getLocation({
        accuracy: '10m',
        autoStop: true,
        filter: 1,
    }, function (ret, err) {
        if (ret.status) {
            vm.loginUserInfo.Lat = ret.lat;
            vm.loginUserInfo.Lng = ret.lon;
        } else {
            vm.loginUserInfo.Lat = 30.663278;
            vm.loginUserInfo.Lng = 104.07176;
        }
    });
}


function switchPwdOrAuthCode(bool) {
    vm.usePwdLogin = bool;
}

function banA(elem) {
    const a = document.querySelector(elem);
    a.classList.add('disable');
}

function unBanA(elem) {
    const a = document.querySelector(elem);
    a.classList.remove('disable');
}

function keyup() {
    if (vm.reqData.tel.length === 11 && !vm.isReqCode) {
        unBanA('.auth-code-btn');
    }
}

async function getAuthCode() {
    const vip = await isVip(vm.reqData.tel);
    if (vip.ok && !vm.isReqCode) {
        vm.isReqCode = true;
        vm.loginOrLogUp = vip.type;

        let second = 60;
        banA('.auth-code-btn');
        setTimeout(function self() {
            second--;
            if (second > 0) {
                vm.getAuthCodeText = `${second}s后重发`;
                setTimeout(self, 1000);
            } else {
                vm.getAuthCodeText = '重新发送';
                unBanA('.auth-code-btn');
                vm.isReqCode = false;
                keyup();
            }
        }, 1000);

        const ok = await fxj.api.getAuthCode(vm.reqData.tel);
        if (!ok) {
            second = 0;
        }
    }
}

async function isVip(str) {
    const result = await ajax({
        url: 'home/userLogin/isVip',
        type: 'post',
        data: {
            phone: str,
        },
    });

    if (result.err !== 0) {
        toast(result.msg);
        return {
            ok: false,
            type: 'err',
        };
    }
    if (result.data.isVip === 1) {
        return {
            ok: true,
            type: 'log in',
        };
    }
    return {
        ok: true,
        type: 'log up',
    };
}

function submit() {
    if (vm.loginOrLogUp === 'log in') {
        login();
    } else if (vm.loginOrLogUp === 'log up') {
        logUp();
    }
}

async function login() {
    let type = 1;
    if (!vm.usePwdLogin) {
        type = 2;
    } else if (vm.loginUserInfo.openId) {
        type = 3;
    }
    const data = {
        Lat: vm.loginUserInfo.Lat,
        Lng: vm.loginUserInfo.Lng,
        pwd: vm.reqData.pwd,
        code: vm.reqData.code,
        phone: vm.reqData.tel,
        openId: vm.loginUserInfo.openId,
        avatar: vm.loginUserInfo.avatar,
        gender: vm.loginUserInfo.gender,
        userName: vm.reqData.tel,
        nickName: vm.loginUserInfo.nickName,
        type,
    };
    const close = fxj.dialog.loading({
        noBg: true,
    });
    const result = await ajax({
        url: 'home/userLogin/logIn',
        type: 'POST',
        data,
    });
    toast(result.msg);
    close();
    if (result.err !== 0) return;
    localStorage.setItem('token', result.data.token);
    localStorage.setItem('_role', '0');
    setTimeout(() => {
        if (result.data.initialLogin === 1) {
            goPage('binding_phone.html');
        } else {
            fxj.closeWin();
        }
    }, 1000);
}

async function logUp() {
    const close = fxj.dialog.loading({
        noBg: true,
    });
    const result = await ajax({
        url: 'home/userRegister/register',
        type: 'POST',
        data: {
            phone: vm.reqData.tel,
            code: vm.reqData.code,
            type: 1,
        },
    });
    close();
    toast(result.msg);
    if (result.err === 0) {
        localStorage.setItem('token', result.data.token);
        localStorage.setItem('_role', '0');
        fxj.dialog.alert({
            title: '恭喜您成功注册分享家账号',
            msg: `
                <div style="display: -webkit-flex;-webkit-flex-direction: column;text-align: left">
                    <div>您的用户名为:分享家xxx</div>
                    <div>默认密码为手机后6位</div>
                    <div>您可以通过<span style="color: orange">我</span>-><span style="color: orange">设置</span>-><span style="color: orange">修改密码</span>修改登陆密码</div>
                </div>`.trim(),
            btnLeft: '我知道啦',
            btn: 1,
            leftCallback: () => {
                console.log('ok');
                fxj.closeWin();
            },
        });
    }
}

function wxLogin() {
    const wx = api.require('wx');
    wx.auth({
        apikey: 'wx43d54fd7031eda6e',
    }, (ret, err) => {
        if (ret.status) {
            wxGetToken(wx, ret.code);
        } else {
            let errMsg = new Map([
                [-1, '请使用账号密码登录'],
                [3, '请使用账号密码登录'],
            ]);
            const msg = errMsg.get(Number(err.code));
            msg && toast(msg);
        }
    });
}

function weiboLogin() {
    const wb = api.require('weibo');
    wb.auth((ret, err) => {
        if (ret.status) {
            getWeiBoUserInfo(wb, ret.token, ret.userId);
        } else {
            let errMsg = new Map([
                [-1, 'apiKey 或 registUrl 值非法'],
                [2, '发送失败'],
                [3, '授权失败'],
                [4, '不支持的请求'],
                [5, '未知错误'],
            ]);
            const msg = errMsg.get(Number(err.code));
            msg && mui.toast(msg);
        }
    });
}

function qqLogin() {
    const qq = api.require('qq');
    qq.login((ret) => {
        if (ret.status) {
            vm.loginUserInfo.openId = ret.openId;
            getQqUserInfo(qq);
        }
    });
}

function getQqUserInfo(qq) {
    qq.getUserInfo((result, err) => {
        if (result.status) {
            setLoginUserInfo({
                avatar: result.info.figureurl_qq_2,
                sex: result.info.gender === '女' ? 0 : 1,
                nickName: result.info.nickname,
            });
        }
    });
}

function wxGetToken(wx, code) {
    wx.getToken({
        apiKey: 'wx43d54fd7031eda6e',
        apiSecret: '531714a20ac6b92a33debd32f2697ff7',
        code,
    }, (result, err) => {
        if (result.status) {
            vm.loginUserInfo.openId = result.openId;
            getWxUserInfo(wx, result.accessToken, result.openId);
        }
    });
}

function getWxUserInfo(wx, accessToken, openId) {
    wx.getUserInfo({
        accessToken,
        openId,
    }, (result, err) => {
        if (result.status) {
            setLoginUserInfo({
                avatar: result.headimgurl,
                sex: result.sex,
                nickName: result.nickname,
            });
        }
    });
}

function setLoginUserInfo({
    avatar = vm.loginUserInfo.avatar,
    sex = vm.loginUserInfo.sex,
    nickName = vm.loginUserInfo.nickName,
}) {
    vm.loginUserInfo.avatar = avatar;
    vm.loginUserInfo.gender = sex;
    vm.loginUserInfo.nickName = nickName;
    submit();
}

function getWeiBoUserInfo(wb, token, userId) {
    wb.getUserInfo({
        token,
        userId,
    }, (result, err) => {
        if (result.status) {
            vm.loginUserInfo.openId = result.userInfo.id;
            setLoginUserInfo({
                avatar: result.userInfo.avatar_hd,
                sex: result.userInfo.gender === 'initSelectDateBox' ? 0 : 1,
                nickName: result.userInfo.name,
            });
        }
    });
}

function doLogin(evt) {
    if (evt.keyCode === 13 || evt.code === 'Enter') {
        login();
    }
}

function doLoginOrLogUp(evt) {
    if (evt.keyCode === 13 || evt.code === 'Enter') {
        submit();
    }
}